#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Author  : 张亦辰
# @Copyright (c) Copyright 2025 张亦辰，All rights reserved。
# @File    : main.py
# @Software: PyCharm
# @Time    : 2025/2/2 21:47

"""
程序说明:
Fen协议的支持
"""
from src.board.pieces import const, exec_piece, Pieces


def from_fen(f: str):
    """
    通过FEN串初始化棋局
    """

    result: list[Pieces] = []
    # 行变量
    y = 0
    # 列变量
    x = 0
    s = __analysis_space(f)[0]

    index = 0
    if index == len(s):
        return result
    c = s[index]
    while c != " ":
        if c == '/':
            # 换行
            x = 0
            y += 1
            if y > 9:
                break
        elif '1' <= c <= '9':
            #  出现空位 列向量x增加c
            x += int(c)
        elif "A" <= c <= "Z":
            # 红方棋子,将字符表示的棋子创建为棋子实例，并放入数组中
            if x <= 8:
                # 判断一下，是否为有效的棋子字符
                if c in const.fen_map.keys():
                    p_class = const.fen_map[c]
                    piece = exec_piece(p_class, const.playerRed, x, y)
                    result.append(piece)
                x += 1
        elif "a" <= c <= "z":
            # 黑方棋子,将字符表示的棋子创建为棋子实例，并放入数组中
            if x <= 8:
                if c in const.fen_map.keys():
                    p_class = const.fen_map[c]
                    piece = exec_piece(p_class, const.playerBlack, x, y)
                    result.append(piece)
                x += 1

        index += 1
        if index == len(s):
            return result
        c = s[index]
    return result


def to_fen(fen: str):
    """
    转换成fen格式
    :param fen:
    :return:
    """
    pass


def __analysis_space(f: str):
    """
    解析 第一层，以空格为分隔
    :param f:
    :return:
    """
    return f.split(' ')
